﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;
using Spring.Context.Support;

namespace Wekit.Core
{
  
    public class WekitControllerFactory : System.Web.Mvc.DefaultControllerFactory
    {
        public static readonly WebApplicationContext ApplicationContext = ContextRegistry.GetContext() as WebApplicationContext;
        public WekitControllerFactory()
        { 
        }
     
       override public IController CreateController(RequestContext requestContext, string controllerName)
       {
           
           string area = GetArea(requestContext);
           string objectId;
           if (!String.IsNullOrEmpty(area))
           {
               objectId = area + "_" + StringUtil.upperFirstLetter(controllerName);
           }
           else
           {
               objectId = StringUtil.upperFirstLetter(controllerName);
           }
           if (ApplicationContext.ContainsObject(objectId))
           {
               return ApplicationContext.GetObject(objectId) as IController;

           }
           else
           {
               return base.CreateController(requestContext, controllerName);
           }
       }

       private string GetArea(RequestContext context)
        {
            if (context.RouteData.DataTokens.ContainsKey("area"))
            {
                return StringUtil.upperFirstLetter(context.RouteData.DataTokens["area"].ToString());
            }

            return string.Empty;
        }

       override public void ReleaseController(IController controller)
       {
           var disposable = controller as IDisposable;
           if (disposable != null)
           {
               disposable.Dispose();
           }
       }
    }
}
